package com.yunnuo.com.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.yunnuo.com.core.PageReq;
import com.yunnuo.com.domain.dto.SysUserReqDto;
import com.yunnuo.com.domain.entity.SysUser;
import com.yunnuo.com.exception.user.UserException;
import groovy.util.logging.Slf4j;

import java.util.Date;
import java.util.Objects;

/**
 * User 服务接口
 *
 * @author yunnuo
 * @since 2022-04-09
 */
@Slf4j
public interface SysUserService extends IService<SysUser> {


    /**
     * 用户数据分页
     *
     * @param pageReq 页面请求
     * @return {@link IPage}<{@link SysUser}>
     */
    IPage<SysUser> pageUsers(PageReq pageReq);

    /**
     * 通过用户id获取所在库和表
     *
     * @param id id
     * @return {@link String}
     */
    default String getLibraryAndTableByUserId(Long id) {
        if (Objects.isNull(id)) {
            throw new UserException("id mast be not null!");
        }
        long library = id % 8L;
        long table = id % 10L;
        return "所在库：" + library + " 所在表：" + table;
    }

    /**
     * 保存用户信息
     *
     * @param reqDto {@link SysUserReqDto}
     * @return {@link SysUser}
     */
    default SysUser saveUserInfo(SysUserReqDto reqDto) {
        try {
            SysUser sysUser = BeanUtil.copyProperties(reqDto, SysUser.class);
            sysUser.setCreateTime(new Date());
            boolean saveFlag = this.save(sysUser);
            if (saveFlag) {
                return sysUser;
            }
            throw new UserException("新增用户数据-0");
        } catch (Exception e) {
            throw new UserException("新增用户失败：" + e.getMessage());
        }
    }
}
